<template>
  <el-dialog
    v-model="authorityVisible"
    draggable
    @close="calcAdd(forRolemRef)"
    :title="title"
    size="70%"
  >
    <el-form
      layout="vertical"
      label-width="auto"
      :rules="rules"
      :model="authorityForm"
      ref="forRolemRef"
    >
      <el-row class="h-full w-full" :gutter="20">
        <el-col :span="12" class="h-full">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="authorityForm.name" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="h-full">
          <el-form-item label="角色状态" prop="stat">
            <el-select v-model="authorityForm.stat" placeholder="请选择">
              <el-option label="使用中" value="ENABLE" />
              <el-option label="禁用" value="DISABLE" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="h-full w-full" :gutter="20">
        <el-col :span="24" class="h-full">
          <el-form-item label="角色说明" prop="explains">
            <el-input v-model="authorityForm.explains" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="h-full w-full" :gutter="20">
        <el-col :span="24" class="h-full">
          <el-form-item label="人员">
            <el-button class="w-full" type="primary" @click="selectPeople"
              >选择人员</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="h-full w-full" :gutter="20">
        <el-col :span="24" class="h-full">
          <el-form-item label="">
            <el-input
              class="w-full"
              disabled
              type="textarea"
              :rows="4"
              v-model="userName"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="h-full w-full" :gutter="20">
        <el-col :span="24" class="h-full">
          <el-form-item label="控件">
            <div class="tree-content w-full">
              <el-tree
                v-model="menus"
                ref="treeMenusRef"
                style="max-width: 600px"
                :data="menuDataList"
                show-checkbox
                default-expand-all
                node-key="id"
                highlight-current
                :props="defaultProps"
              />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="h-full w-full" :gutter="20">
        <el-col :span="24" class="h-full"> 数据纬度 </el-col>
      </el-row>
      <el-row class="h-full w-full" :gutter="20">
        <el-col :span="24" class="h-full">
          <el-form-item label="公司名称" prop="companys">
            <el-select
              multiple
              v-model="authorityForm.companys"
              placeholder="请选择"
            >
              <el-option
                v-for="item in companyList"
                :key="item.companyCode"
                :label="item.companyName"
                :value="item.companyCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="h-full w-full" :gutter="20">
        <el-col :span="24" class="h-full tx-c">
          <el-button type="default" @click="calcAdd(forRolemRef)"
            >取消</el-button
          >
          <el-button type="primary" @click="onConfirm(forRolemRef)"
            >确认</el-button
          >
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
  <el-dialog
    v-model="dialogVisible"
    title="选择人员"
    draggable
    width="500"
    :before-close="handleClose"
  >
    <div>
      <el-tree-select
        ref="treePeopleRef"
        v-model="users"
        style="max-width: 600px"
        :data="peopleTreeData"
        show-checkbox
        :default-expand-all="false"
        filterable
        multiple
        node-key="deptId"
        highlight-current
        @check-change="handleCheckChange"
        :props="defaultProps"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onConfirmDialog"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import {
  addRole,
  updateRole,
  getCurrentRoleDetailApi
} from '@/api/modules/authority.js'
import { ElMessage } from 'element-plus'
import { inject, ref, reactive } from 'vue'
const emit = defineEmits(['getCurrent'])
const authorityVisible = ref(false)
const users = ref()
const userName = ref([])
const treeMenusRef = ref(null)
const menus = ref([])
const treePeopleRef = ref(null)
const forRolemRef = ref(null)
const title = ref('新增')
const rules = reactive({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
})
const onConfirmDialog = () => {
  dialogVisible.value = false
  let userNames = ''
  let userIds = []
  console.log(treePeopleRef.value.getCheckedNodes(false, false), 555555)
  const selectPeopleList = JSON.parse(
    JSON.stringify(treePeopleRef.value.getCheckedNodes(false, false))
  )
  selectPeopleList.forEach(item => {
    if (item.type === 'user' && !userNames.includes(item.label)) {
      userNames += item.label + ', '
      userIds.push(item.id)
    }
  })
  console.log(userNames, 333333)
  userName.value = userNames?userNames.substr(0, userNames.length - 2):''
  console.log(userName, 4444444)
  users.value = userIds
}

const onConfirm = async formEl => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      const params = authorityForm.value
      params.users = users.value
      params.menus = []
      params.views = []
      params.bottoms = []
      const menusSelect = JSON.parse(
        JSON.stringify(treeMenusRef.value.getCheckedNodes(false, false))
      )
      if (menusSelect && menusSelect.length) {
        menusSelect.forEach(item => {
          if (item.menuType === 'menu') {
            params.menus.push(item.value)
          }
          if (item.menuType === 'view') {
            params.views.push(item.value)
          }
          if (item.menuType === 'bottom') {
            params.bottoms.push(item.value)
          }
        })
      }
      if (title.value === '新增') {
        addRoleApi(params)
        return
      }
      updateRoleApi(params)
    } else {
      console.log('error submit!', fields)
    }
  })
}

const addRoleApi = async params => {
  delete params.bottomIds
  delete params.companyIds
  delete params.menuDataList
  delete params.userIds
  delete params.viewIds
  delete params.menuIds
  const { code } = await addRole(params)
  if (code === 200) {
    ElMessage.success('成功!')
    emit('getCurrent')
    calcAdd()
  }
}

const updateRoleApi = async params => {
  delete params.bottomIds
  delete params.companyIds
  delete params.menuDataList
  delete params.userIds
  delete params.viewIds
  delete params.menuIds
  const { code } = await updateRole(params)
  if (code === 200) {
    ElMessage.success('成功!')
    emit('getCurrent')
    calcAdd()
  }
}
const calcAdd = () => {
  users.value = []
  menus.value = []
  treeMenusRef.value.setCheckedKeys([], false)
  userName.value = []
  authorityVisible.value = false
  forRolemRef.value.resetFields()
}
const {
  authorityForm,
  selectPeople,
  defaultProps,
  menuDataList,
  companyList,
  dialogVisible,
  handleClose,
  peopleTreeData,
  personList
} = inject('modules').addAddAuthorityStore

const getCurrentRoleDetail = async id => {
  const { data } = await getCurrentRoleDetailApi(id)
  data.menus = data.menus || []
  data.views = data.views || []
  data.bottoms = data.bottoms || []
  menus.value = data.menus.concat(data.views.concat(data.bottoms))
  data.users = data.users || []
  users.value = data.users
  userName.value = data.users.map(item => {
    let name = ''
    personList.value.forEach(ite => {
      if (ite.userid === item.split('=')[1]) {
        name = ite.name
      }
    })
    return name
  })
  authorityForm.value = { ...data }
  treeMenusRef.value.setCheckedKeys(menus.value, true)
}

defineExpose({
  getCurrentRoleDetail,
  authorityVisible,
  title
})
</script>
<style lang="scss" scoped>
.tx-c {
  text-align: center;
}
.tree-content {
  max-height: 200px;
  overflow: auto;
}
</style>
